//利用localStorage来存取数据

var store = {

	save(key, value) {

		localStorage.setItem(key, JSON.stringify(value))

	},

	fetch(key) {

		return JSON.parse(localStorage.getItem(key)) || [];
	}

}

// var list=[

// 	{
// 		title:'vue实例',

// 		isChecked:false //false 未选中

// 	},
// 	{
// 		title:'vue实例',

// 		isChecked:true //true 选中

// 	}

// ]


//取出所有的值
var list = store.fetch('miaov');


var filter = {
	all: function (list) {
		return list;
	},
	finished: function (list) {
		return list.filter(function (item) {
			return item.isChecked;
		})
	},
	unfinished: function () {
		return list.filter(function (item) {
			return !item.isChecked;
		})
	}
}

//vue实例
var vm = new Vue({

	el: ".main",

	data: {

		list: list,

		todo: '',

		editTodos: '',

		before_title: '',

		visibility: "all" //通过这个属性值的变化对数据进行筛选

	},

	watch: {

		list: { //监控list这个属性，当这个属性对应的值发生变化就会执行函数
			handler: function () {
				store.save("miaov", this.list);
			},
			deep: true //深度监控
		}
	},

	computed: {

		unCheckedNum: function () {

			return this.list.filter(function (item) {

				return !item.isChecked

			}).length
		},

		filteredList: function () {
			//找到了过滤函数，就返回过滤后的数据；如果没有返回所有数据
			return filter[this.visibility] ? filter[this.visibility](list) : list;

		}
	},

	methods: {

		addTodo: function () { //添加任务

			//事件处理函数中的this指向的是当前的根实例
			this.list.push({

				title: this.todo,

				isChecked: false

			});

			this.todo = '';
		},


		deleteTodo: function (todo) {

			var index = this.list.indexOf(todo);

			this.list.splice(index, 1);
		},

		editTodo: function (todo) {

			//保存编辑前的title，方便取消编辑的时候使用
			this.beforeTitle = todo.title;

			this.editTodos = todo;
		},

		editTodoed: function (todo) {

			this.editTodos = '';

		},

		cancelEditTodo(todo) {

			todo.title = this.beforeTitle;

			this.beforeTitle = '';

			this.editTodos = '';

		}
	}

})

function watchHashChange() {
	var hash = window.location.hash.slice(1);

	vm.visibility = hash;

}

watchHashChange();

window.addEventListener("hashchange", watchHashChange);